import React, { useEffect, useRef, useState } from 'react';

import { marketVerifyCode, marketOfferOrder, marketSelectToken } from './api';
import FlowCustomer from './components/flow_customer';
import ProtocolDialog from './components/protocol_dialog/index';
import { showToast } from './utils';

const closeIcon =
  '';

const CAPTCHA_TIME = 60;
let smsFlag = false;
let submitFlag = false;
let tokenFlag = false;
export default function IndexPage(props) {
  const [id, setId] = useState('1');
  // 电话
  const [tel, setTel] = useState('');
  // 验证码
  const [captcha, setCaptcha] = useState('');
  // 验证码显示时间
  const [captchaTime, setCaptchaTime] = useState(0);
  // jdk获取toekn
  const [token, settoken] = useState();
  // 验证码计算时间和timer
  const captchaTimer = useRef({});

  const [protocolDialogShow, setprotocolDialogShow] = useState(false);
  const [confitmDialog, setConfitmDialog] = useState(false);
  // 显示二确弹窗
  const [showProtocol, setShowProtocol] = useState(false);
  // 显示客服弹窗
  const [showCustomer, setShowCustomer] = useState(false);
  const [orderId, setorderId] = useState('');
  const [codeList] = useState(['mo0pWlH262']);

  useEffect(() => {
    window.document.body.style.overflow = showProtocol || confitmDialog ? 'hidden' : '';
  }, [showProtocol, confitmDialog]);
  useEffect(() => {
    let id = window.location.search;
    if (id) {
      setId(id.split('id=')[1]);
    }
  }, [window.location.search]); // eslint-disable-line

  function startCaptchaTimer() {
    if (captchaTimer.current.timer) {
      clearInterval(captchaTimer.current.timer);
    }
    captchaTimer.current.time = CAPTCHA_TIME;
    captchaTimer.current.timer = setInterval(() => {
      captchaTimer.current.time--;
      setCaptchaTime(captchaTimer.current.time);
      if (captchaTimer.current.time <= 0) {
        clearInterval(captchaTimer.current.timer);
        captchaTimer.current.timer = null;
      }
    }, 1000);
  }
  async function handleSendCaptcha() {
    if (smsFlag) return;
    if (captchaTime > 0) return;
    smsFlag = true;
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    }
    window.channelSDK().then((d) =>
      setTimeout(() => {
        getToken();
      }, 500)
    );
    try {
      let res = await marketVerifyCode({ phoneNum: tel, goodsCode: codeList[id - 1] });
      if (res.code === 200) {
        startCaptchaTimer();
        setorderId(res.data.orderId);
        showToast(res.data?.tipsMsg ? res.data.tipsMsg : res.msg ?? '发送成功');
      } else {
        showToast(res.data?.tipsMsg ? res.data.tipsMsg : res.msg ?? '发送失败，请确认是否有办理权限');
      }
    } catch (e) {
      showToast(e.message ?? '发送失败，请确认是否有办理权限');
    } finally {
      smsFlag = false;
    }
  }
  async function handleConfirm() {
    if (tokenFlag) return;
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    } else if (!captcha) {
      return showToast('请输入验证码');
    }
    tokenFlag = true;
    window.channelSDK().then((d) =>
      setTimeout(() => {
        getToken();
      }, 500)
    );
    setShowProtocol(true);
  }
  async function getToken() {
    try {
      const res = await marketSelectToken({ data: 'kgj' });
      if (res.code === 200) {
        settoken(res.data);
      } else {
      }
    } catch (error) {
    } finally {
      tokenFlag = false;
    }
  }
  // 最终提交
  async function handleNextConfirm() {
    if (submitFlag) return;
    submitFlag = true;
    if (!tel || /^1[0-9]{10}$/.test(tel) !== true) {
      return showToast('请输入正确的手机号');
    } else if (!captcha) {
      return showToast('请输入验证码');
    }
    try {
      let res = await marketOfferOrder({
        phoneNum: tel,
        goodsCode: codeList[id - 1],
        verifyCode: captcha,
        orderSn: orderId,
        token: token,
      });
      if (res.code === 200) {
        setShowProtocol(false);
        setConfitmDialog(true);
      } else {
        showToast(res.data?.tipsMsg ?? '办理失败');
      }
    } catch (e) {
      showToast(e.message ?? '办理失败');
    } finally {
      submitFlag = false;
    }
  }
  const handleClick = () => {
    setConfitmDialog(false);
    setTel('');
    setCaptcha('');
    setCaptchaTime(0);
    settoken('');
  };

  return (
    <div className="index-page">
      <img className="top-pic" src={`/pic/${id}_top.png`} alt="" />
      {/* <img alt="" className="float-customer-btn" src="/pic/pic_4.png" onClick={() => setShowCustomer(!showCustomer)} /> */}
      <div className="form-block">
        <div className="prop-line">
          <span className="icon">+86</span>
          <input
            id="tellphone"
            className="prop-input"
            placeholder="请输入手机号"
            value={tel}
            onChange={(e) => setTel(e.currentTarget.value)}
          />
        </div>
        <div className="prop-line">
          <input
            id="msgCode"
            className="prop-input captcha"
            placeholder="请输入验证码"
            value={captcha}
            onChange={(e) => setCaptcha(e.currentTarget.value)}
          />
          <div id="getCode" className={`btn-captcha ${captchaTime > 0 ? 'disabled' : ''}`} onClick={handleSendCaptcha}>
            {captchaTime > 0 ? captchaTime + 's' : '获取验证码'}
          </div>
        </div>

        <div className="btn-confirm" onClick={handleConfirm} id="toApply">
          立即订购
        </div>
      </div>
      <img alt="" className="top-pic" mode="widthFix" src={`/pic/${id}_dtl.png`} />
      <div className={`order-dialog ${showProtocol ? '' : 'd-none'}`}>
        <div className="order-mask" onClick={() => setShowProtocol(false)} />
        <div className="order-center" onClick={() => {}}>
          <img className="img-box" src="./pic/1_dialog.jpg" alt="" />
          <div className="close-btn" onClick={() => setShowProtocol(false)}>
            <img className="img" src={closeIcon} alt="" />
          </div>
          <div className="tips-block">您的手机{tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}正在订购</div>
          <div className="btn-block">
            <div className="btn" onClick={() => setShowProtocol(false)}>
              我在想想
            </div>
            <div
              id="confirm"
              className="btn confirm-btn"
              onClick={() => {
                setShowProtocol(false);
                handleNextConfirm();
              }}
            >
              确认订购
            </div>
          </div>
        </div>
      </div>
      <img alt="" className="top-pic" mode="widthFix" src={`/pic/${id}_base.png`} />
      {protocolDialogShow ? <ProtocolDialog onClose={() => setprotocolDialogShow('')} /> : null}

      {showCustomer ? <FlowCustomer tel="15238380662" onClose={() => setShowCustomer(false)} /> : null}
      {confitmDialog && (
        <div className="protocol-dialog">
          <div className="close-btn" onClick={() => handleClick()}>
            <img className="img" src={closeIcon} alt="" />
          </div>
          <img className="success-img" src={`/pic/${id}_ok.png`} alt="" onClick={() => handleClick()} />
        </div>
      )}
    </div>
  );
}
